package cn.itcast.web.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        if(cookies!=null&&cookies.length>0){
            for (Cookie c:cookies) {
                String name = c.getName();
                if ("lasttime".equals(name)){
                    flag = true;
                    String value = c.getValue();
                    String decode = URLDecoder.decode(value,"utf-8");
                    response.getWriter().write("欢迎回来，你上次访问的时间是"+decode);
                    Date date = new Date();
                    SimpleDateFormat slf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String format = slf.format(date);
                    String encode = URLEncoder.encode(format, "utf-8");
                    c.setValue(encode);
                    c.setMaxAge(60*60*24*30);
                    response.addCookie(c);
                    break;
                }

            }
        }
        if (cookies==null||cookies.length==0||flag==false){
            response.getWriter().write("欢迎首次访问");
            Date date = new Date();
            SimpleDateFormat slf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String format = slf.format(date);
            String encode = URLEncoder.encode(format, "utf-8");
            Cookie c = new Cookie("lasttime", encode);
            c.setMaxAge(60*60*24*30);
            response.addCookie(c);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
